# Create your views here.
import math
import os, json
from datetime import datetime
from openpyxl import Workbook
from finance.models import Dimission
from personal_center.models import User
from django.views import View
from django.db.models import Q, Count
from openpyxl.styles import Alignment, Font
from openpyxl.styles.borders import Border, Side
from administrative.models import Company, Topics, ConferenceMemo
from django.shortcuts import render, HttpResponse, redirect
from logistics.MessagePushOperationRecords import RecordAndPush
from medical_ethics.create_excel import DownloadPublishTheResults
from medical_ethics.models import EvaluationOfMedicalEthics, EvaluationOpinion, EvaluationTeam


class MedicalEthicsMyApplyView(View):
    def get(self, request):
        user = request.user
        context = {'realname': request.user.real_name, 'position': request.user.post}
        return render(request, 'medical_ethics/medical_ethics_myapply.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        objs = user.evaluationofmedicalethics_set.all().order_by('-create_time')

        data_list = [
            {'id': obj.id, 'apply_user': obj.apply_user.real_name, 'apply_company': (("医德医风评选一组" if int(obj.apply_company_id) == 1001 else "医德医风评选二组" if int(obj.apply_company_id) == 1002 else "医德医风评选三组" if int(obj.apply_company_id) == 1003 else "医德医风评选四组") if int(obj.apply_company_id) > 1000 else Company.objects.get(id=int(obj.apply_company_id)).name) if (obj.apply_company_id and obj.apply_company_id != "0") else "",
             'title': obj.title, "current_audit_users": ' ,'.join([i.real_name for i in obj.current_audit_users.all()]),
             'state': obj.get_state_str(), 'level': obj.get_level_display(), 'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"),
             'url': '<a class="plugin-action" href="MedicalEthicsDraft.html?id='+str(obj.id)+'">修改</a>' if obj.state == 'draft' else '<a class="plugin-action" id="'+str(obj.id)+'" '
             'href="medical_ethics_detail_view?id='+str(obj.id)+'">查看</a>'
             } for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class save_from(View):
    def post(self, request):
        flow_id = request.POST.get('flow_id', '')             # 流程id
        company_id = request.POST.get('Department_office', '')       # 科室id
        education = request.POST.get('whcd', '')
        gender = request.POST.get('gender', '')                           # 男传 male 女传 female
        birthday_date = request.POST.get('birthday', '')             # 格式 '2022-08-15'
        employ_date = request.POST.get('pysj', '')                 # 格式 '2022-08-15'
        job = request.POST.get('work_is', '')
        political_status = request.POST.get('zzmm', '')
        professional_title = request.POST.get('rank', '')
        content = request.POST.get('work_text', '')
        title = request.POST.get('title', '')
        year = request.POST.get('year_num', '')

        history_obj = EvaluationOfMedicalEthics.objects.filter(~Q(state='draft'), apply_user=request.user, year=int(year)).count()
        if history_obj > 0:
            returnDict = {'code': 500, 'message': '您今年的医德医风考评已提交, 无需保存!'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        if flow_id:
            obj = EvaluationOfMedicalEthics.objects.get(id=int(flow_id))
            if company_id:
                obj.apply_company_id = int(company_id)
            obj.education = education
            obj.gender = gender
            obj.birthday_date = birthday_date
            obj.employ_date = employ_date
            obj.job = job
            obj.political_status = political_status
            obj.professional_title = professional_title
            obj.content = content
            obj.title = title
            obj.year = int(year)
        else:
            obj = EvaluationOfMedicalEthics.objects.create(apply_user=request.user, apply_company_id=int(company_id) if company_id != 'undefined' else "", education=education,
                                                           gender=gender, birthday_date=birthday_date, employ_date=employ_date, job=job, political_status=political_status,
                                                           professional_title=professional_title, content=content, title=title, year=int(year))
        obj.state = 'draft'
        obj.save()
        returnDict = {'code': 200, 'message': '保存成功!'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class MedicalEthicsView(View):
    def get(self, request):
        real_name = request.user.real_name
        position = request.user.post
        department = request.user.company.name
        today = datetime.today()
        year_num = today.year - 1
        obj_count = EvaluationTeam.objects.filter(company=request.user.company).count()
        Company_obj = Company.objects.filter(~Q(id=87)).order_by("serial_number")
        team_list = []
        for team in Company_obj:
            if not EvaluationTeam.objects.filter(company=team).count():
                team_list.append({"id": team.id, "name": team.name})
        signature_flag = "true"
        if not request.user.signature_picture or "new_user.html" in str(request.user.signature_picture):
            signature_flag = "false"
        context = {"realname": real_name, "department": department, "position": position, 'year_num': year_num, "team_flag": "true" if obj_count else "false",
            'company_list': [{"id": c.id, "name": c.name} for c in Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")], "team_list": team_list, "signature_flag": signature_flag}
        return render(request, 'medical_ethics/medical_ethics.html', context)

    def post(self, request):
        flow_id = request.POST.get('flow_id', '')  # 流程id
        company_id = request.POST.get('Department_office', '')  # 科室id
        education = request.POST.get('whcd', '')
        gender = request.POST.get('gender', '')  # 男传 male 女传 female
        birthday_date = request.POST.get('birthday', '')  # 格式 '2022-08-15'
        employ_date = request.POST.get('pysj', '')  # 格式 '2022-08-15'
        job = request.POST.get('work_is', '')
        political_status = request.POST.get('zzmm', '')
        professional_title = request.POST.get('rank', '')
        content = request.POST.get('work_text', '')
        title = request.POST.get('title', '')
        year = request.POST.get('year_num', '')
        try:
            RecordAndPush().OperationRecords(request, "医德医风")
        except:
            pass
        history_obj = EvaluationOfMedicalEthics.objects.filter(~Q(state='draft'), apply_user=request.user, year=int(year)).count()
        if history_obj > 0:
            returnDict = {'code': 500, 'message': '您今年的医德医风考评已提交,不用重复提交!'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        if flow_id:
            obj = EvaluationOfMedicalEthics.objects.get(id=int(flow_id))
            obj.apply_company_id = int(company_id)
            obj.education = education
            obj.gender = gender
            obj.birthday_date = birthday_date
            obj.employ_date = employ_date
            obj.job = job
            obj.political_status = political_status
            obj.professional_title = professional_title
            obj.content = content
            obj.title = title
            obj.year = int(year)
        else:
            obj = EvaluationOfMedicalEthics.objects.create(apply_user=request.user, apply_company_id=int(company_id), education=education, gender=gender, birthday_date=birthday_date,
                                      employ_date=employ_date, job=job, political_status=political_status, professional_title=professional_title, content=content, title=title, year=int(year))

        obj.state = "one"
        obj.save()
        if int(company_id) == 1001:
            one_appave = Company.objects.get(id=3).head_people
        elif int(company_id) == 1002:
            one_appave = Company.objects.get(id=30).head_people
        elif int(company_id) == 1003:
            one_appave = Company.objects.get(id=23).head_people
        elif int(company_id) == 1004:
            one_appave = Company.objects.get(id=25).head_people
        else:
            one_appave = Company.objects.get(id=int(company_id)).head_people

        EvaluationOpinion.objects.create(parent_id=obj, audit_people=one_appave, node='one', audit_note='')
        obj.current_audit_users.add(one_appave)
        EvaluationOpinion.objects.create(parent_id=obj, audit_people=request.user, node='two', audit_note='同意考核结果。', state='audit')
        topic_type = "医德医风"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.content[:15] + "……" if len(obj.content) > 15 else obj.content
        try:
            RecordAndPush().MessagePush(one_appave.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
        except:
            pass
        returnDict = {'code': 200, 'message': '创建成功!'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class OverviewEvaluation(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        today = datetime.today()
        year_num = today.year - 1
        objs = EvaluationOfMedicalEthics.objects.filter(state__in=['three', 'five'], year=year_num).order_by('create_time')

        CompanyObj = objs.all().values("apply_company_id").distinct()
        YearObj = objs.all().values("year").distinct()
        year_list = []
        for years in YearObj:
            year_list.append(years["year"])

        dep_dict_list, set_list = [], []
        for jjj in CompanyObj:
            if int(jjj["apply_company_id"]) == 1001:
                CompanyName = "医德医风评选一组"
            elif int(jjj["apply_company_id"]) == 1002:
                CompanyName = "医德医风评选二组"
            elif int(jjj["apply_company_id"]) == 1003:
                CompanyName = "医德医风评选三组"
            elif int(jjj["apply_company_id"]) == 1004:
                CompanyName = "医德医风评选四组"
            else:
                CompanyName = Company.objects.get(id=jjj["apply_company_id"]).name

            if CompanyName not in set_list:
                dep_dict_list.append({"value": jjj["apply_company_id"], "name": CompanyName})
                set_list.append(CompanyName)

        morals_wind_flag = False
        eva_obj = EvaluationOfMedicalEthics.objects.filter(state="three")
        if eva_obj.count():
            morals_wind_flag = True

        dept_name = '请选择部门'
        return render(request, 'medical_ethics/OverviewEvaluation.html', {'realname': real_name, 'position': position, 'department': department, "year_list": year_list,
        "year_num": year_num, "dept_id": "", "dept": dept_name, "dep_dict_list": dep_dict_list, "morals_wind_flag": morals_wind_flag})

    def post(self, request):
        today = datetime.today()
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", '')  # 查询关键词
        LevalType = request.POST.get("LevalType", '')
        year = request.POST.get('search_year', today.year - 1)           # 年份查询
        dept = request.POST.get('search_dept', '')           # 查询部门

        if dept:
            objs = EvaluationOfMedicalEthics.objects.filter(Q(apply_user__real_name__contains=search_data) | Q(title__contains=search_data) | Q(education__contains=search_data) |
                Q(employ_date__contains=search_data) | Q(birthday_date__contains=search_data) | Q(job__contains=search_data) | Q(political_status__contains=search_data) |
                Q(apply_company_id__contains=search_data) | Q(professional_title__contains=search_data), state__in=['three', 'five'], year=year, level__contains=LevalType, apply_company_id=dept).order_by('create_time')
        else:
            objs = EvaluationOfMedicalEthics.objects.filter(Q(apply_user__real_name__contains=search_data) | Q(title__contains=search_data) | Q(education__contains=search_data) |
                Q(employ_date__contains=search_data) | Q(birthday_date__contains=search_data) | Q(job__contains=search_data) | Q(political_status__contains=search_data) |
                Q(apply_company_id__contains=search_data) | Q(professional_title__contains=search_data), state__in=['three', 'five'], year=year, level__contains=LevalType).order_by('create_time')

        data_list = []
        for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]:
            status = "未提交" if obj.get_state_str() == "已提交" else obj.get_state_str()
            if status == "未提交":
                flow_url = '<a class="plugin-action" href="medical_ethics_detail_view?id='+str(obj.id)+'">查看</a> | <a class="plugin-action" onclick="FallLevel('+str(obj.id)+')" href="JavaScript:;" style="color: red;">降级</a> | <a href="javascript:;" onclick="SingleSubmission('+str(obj.id)+')">提交</a> | <a href="javascript:;" style="color: red;" onclick="CommitteeReturn('+str(obj.id)+', \''+obj.apply_user.real_name+'\')">退回</a>'
            elif status == "结束":
                flow_url = '<a class="plugin-action" href="medical_ethics_detail_view?id=' + str(obj.id) + '">查看</a> | <a href="javascript:;" style="color: red;" onclick="CommitteeReturn('+str(obj.id)+', \''+obj.apply_user.real_name+'\')">退回</a>'
            else:
                flow_url = '<a class="plugin-action" href="medical_ethics_detail_view?id='+str(obj.id)+'">查看</a> | <a class="plugin-action" onclick="FallLevel('+str(obj.id)+')" href="JavaScript:;" style="color: red;">降级</a> | <a href="javascript:;" style="color: red;" onclick="CommitteeReturn('+str(obj.id)+', \''+obj.apply_user.real_name+'\')">退回</a>'
            if int(obj.apply_company_id) == 1001:
                company_name = "医德医风评选一组"
            elif int(obj.apply_company_id) == 1002:
                company_name = "医德医风评选二组"
            elif int(obj.apply_company_id) == 1003:
                company_name = "医德医风评选三组"
            elif int(obj.apply_company_id) == 1004:
                company_name = "医德医风评选四组"
            else:
                company_name = Company.objects.get(id=int(obj.apply_company_id)).name
            one_dict = {'id': obj.id, 'apply_user': obj.apply_user.real_name,
                 'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"), "company": company_name,
                 "professional_title": obj.professional_title, "employ_date": obj.employ_date,
                 "job": obj.job, 'level': obj.get_level_display(), 'state': status, 'url': flow_url}
            if status != "完结":
                data_list.insert(0, one_dict)
            else:
                data_list.append(one_dict)
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class AssessmentPublicity(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        today = datetime.today()
        year_num = today.year - 1
        objs = EvaluationOfMedicalEthics.objects.filter(state__in=['three', 'five']).order_by('-year')

        YearObj = objs.all().values("year").distinct()
        year_list = []
        for years in YearObj:
            year_list.append(years["year"])

        CompanyObj = objs.filter(year=year_list[0] if year_list else year_num).values("apply_company_id").distinct()
        # ===========================================================构建表格数据===========================================================
        examine_data_list, serial = [], 1
        for dept in CompanyObj:
            if int(dept["apply_company_id"]) >= 1000:
                if int(dept["apply_company_id"]) == 1001:
                    company_name = "医德医风评选一组"
                elif int(dept["apply_company_id"]) == 1002:
                    company_name = "医德医风评选二组"
                elif int(dept["apply_company_id"]) == 1003:
                    company_name = "医德医风评选三组"
                else:
                    company_name = "医德医风评选四组"
            else:
                company_name = Company.objects.get(id=int(dept["apply_company_id"])).name

            examine_obj = EvaluationOfMedicalEthics.objects.filter(state__in=['three', 'five'], year=year_num, apply_company_id=dept["apply_company_id"]).order_by('create_time')
            # 优秀数据获取
            best_obj = examine_obj.filter(level='best')
            best_prople = '、'.join([i.apply_user.real_name for i in best_obj])
            # =================================================================良好数据获取=================================================================
            good_obj = examine_obj.filter(level='good')
            good_prople = '、'.join([i.apply_user.real_name for i in good_obj])
            # =================================================================一般数据获取=================================================================
            ordinary_obj = examine_obj.filter(level='ordinary')
            ordinary_prople = '、'.join([i.apply_user.real_name for i in ordinary_obj])
            # =================================================================较差数据获取=================================================================
            bad_obj = examine_obj.filter(level='bad')
            bad_prople = '、'.join([i.apply_user.real_name for i in bad_obj])
            examine_data_list.append({"company_name": company_name, "participate_number": examine_obj.count(), "best_prople": best_prople, "best_count": best_obj.count(),
                                      "good_prople": good_prople, "ordinary_prople": ordinary_prople, "bad_prople": bad_prople, "serial": serial})
            serial += 1
        context = {'realname': real_name, 'position': position, 'department': department, "year_num": year_num, "year_list": year_list, "examine_data_list": examine_data_list}
        return render(request, 'medical_ethics/AssessmentPublicity.html', context)

    def post(self, request):
        years = request.POST.get('years', None)
        CompanyObj = EvaluationOfMedicalEthics.objects.filter(state__in=['three', 'five'], year=years).values("apply_company_id").distinct()
        # ===========================================================构建表格数据===========================================================
        examine_data_list, serial = [], 1
        for dept in CompanyObj:
            if int(dept["apply_company_id"]) >= 1000:
                if int(dept["apply_company_id"]) == 1001:
                    company_name = "医德医风评选一组"
                elif int(dept["apply_company_id"]) == 1002:
                    company_name = "医德医风评选二组"
                elif int(dept["apply_company_id"]) == 1003:
                    company_name = "医德医风评选三组"
                else:
                    company_name = "医德医风评选四组"
            else:
                company_name = Company.objects.get(id=int(dept["apply_company_id"])).name
            examine_obj = EvaluationOfMedicalEthics.objects.filter(state__in=['three', 'five'], year=years, apply_company_id=dept["apply_company_id"]).order_by('create_time')
            # 优秀数据获取
            best_obj = examine_obj.filter(level='best')
            best_prople = '、'.join([i.apply_user.real_name for i in best_obj])
            # =================================================================良好数据获取=================================================================
            good_obj = examine_obj.filter(level='good')
            good_prople = '、'.join([i.apply_user.real_name for i in good_obj])
            # =================================================================一般数据获取=================================================================
            ordinary_obj = examine_obj.filter(level='ordinary')
            ordinary_prople = '、'.join([i.apply_user.real_name for i in ordinary_obj])
            # =================================================================较差数据获取=================================================================
            bad_obj = examine_obj.filter(level='bad')
            bad_prople = '、'.join([i.apply_user.real_name for i in bad_obj])
            examine_data_list.append(
                {"company_name": company_name, "participate_number": examine_obj.count(), "best_prople": best_prople, "best_count": best_obj.count(),
                 "good_prople": good_prople, "ordinary_prople": ordinary_prople, "bad_prople": bad_prople, "serial": serial})
            serial += 1
        returnDict = {'code': 200, 'message': '查询成功!', "data": examine_data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class MedicalEthicsDetailView(View):
    def get(self, request):
        id = request.GET.get('id', None)
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        obj = EvaluationOfMedicalEthics.objects.get(id=int(id))

        audit_list, flow_dict = [] , {}
        for audit_obj in obj.evaluationopinion_set.all():
            flow_dict[audit_obj.node] = {'apply': "true" if audit_obj.state == 'audit' else "false", 'apply_people': audit_obj.audit_people.real_name,
                                         'sear': len([i for i in flow_dict]) + 1}
            audit_list.append(
                {'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state == 'audit' else '',
                 'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if audit_obj.state == 'audit' else '',
                 'node': audit_obj.node, "state": audit_obj.state,
                 'audit_note': audit_obj.audit_note, 'audit_people': audit_obj.audit_people.real_name
                 }
            )

        if "three" not in flow_dict:
            flow_dict["three"] = {'apply': "false", 'apply_people': "", 'sear': 3}

        context = {
            "realname": real_name, "department": department, "position": position, "year_num": obj.year, "flow_dict": flow_dict,
            "obj": obj, "item_list": json.loads(obj.item_list) if obj.item_list else "", "audit_list": audit_list, "level": obj.get_level_display(),
            "one_appove_time": obj.evaluationopinion_set.filter(node="one").last().update_time if obj.evaluationopinion_set.filter(node="one", state='audit').count() else "",
            "two_appove_time": obj.evaluationopinion_set.filter(node="two").last().update_time,
            "two_appove_audit": obj.evaluationopinion_set.filter(node="two").last().audit_note,
            "three_appove_time": obj.evaluationopinion_set.filter(node="three").last().update_time if obj.state in ["five"] else "",
            "three_appove_audit": obj.evaluationopinion_set.filter(node="three").last().audit_note if obj.state in ["five"] else "",
            "is_audit": "true" if (obj.evaluationopinion_set.filter(node="one").first().audit_people == request.user and obj.state in ["one", "seven"]) else "false"
        }
        return render(request, 'medical_ethics/medical_ethics_dails.html', context)

    def post(self, request):
        present_id = request.POST.get('id', None)
        obj = EvaluationOfMedicalEthics.objects.get(id=int(present_id))
        obj.audit_users_already.add(request.user)
        item_list = request.POST.get('item_list', None)  # [{'id': 1, 'score': 10}]
        total_score = request.POST.get('total_score', None)
        try:
            RecordAndPush().OperationRecords(request, "医德医风")
        except:
            pass
        if float(total_score) >= 90 and float(total_score) <= 100:
            obj.level = 'best'
        elif float(total_score) >= 80 and float(total_score) < 90:
            obj.level = 'good'
        elif float(total_score) >= 70 and float(total_score) < 80:
            obj.level = 'ordinary'
        else:
            obj.level = 'bad'
        obj.total_score = total_score
        obj.item_list = item_list

        opinion = obj.evaluationopinion_set.filter(node='one', audit_people=request.user).first()
        opinion.update_time = datetime.now()
        opinion.state = 'audit'
        opinion.save()
        obj.state = "seven"
        obj.current_audit_users.clear()
        obj.save()
        returnDict = {'code': 200, 'message': '审批成功!'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")



class MedicalEthicsDraft(View):
    def get(self, request):
        flow_id = request.GET.get('id', None)
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        obj = EvaluationOfMedicalEthics.objects.get(id=int(flow_id))
        today = datetime.today()
        year_num = today.year - 1
        obj_count = EvaluationTeam.objects.filter(company=request.user.company).count()
        Company_obj = Company.objects.filter(~Q(id=87)).order_by("serial_number")
        team_list = []
        for team in Company_obj:
            if not EvaluationTeam.objects.filter(company=team).count():
                team_list.append({"id": team.id, "name": team.name})
        signature_flag = "true"
        if not request.user.signature_picture or "new_user.html" in str(request.user.signature_picture):
            signature_flag = "false"
        context = {"realname": real_name, "department": department, "position": position, "obj": obj, "year_num": year_num, "team_flag": "true" if obj_count else "false",
                   'company_list': [{"id": c.id, "name": c.name} for c in Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")], "team_list": team_list, "signature_flag": signature_flag}
        return render(request, 'medical_ethics/MedicalEthicsDraft.html', context)


class DepartmentSummary(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        today = datetime.today()
        year_num = today.year - 1
        objs = EvaluationOpinion.objects.filter(audit_people=request.user, node='one', parent_id__year=year_num).order_by('create_time')
        if not objs.count():
            objs = EvaluationOpinion.objects.filter(audit_people=request.user, node='one', parent_id__year=today.year).order_by('create_time')

        year_obj = EvaluationOfMedicalEthics.objects.all().order_by("-year").values("year").distinct()
        year_list = []
        for years in year_obj:
            year_list.append(years["year"])

        morals_wind_flag = False
        eva_obj = request.user.evaluationopinion_set.filter(parent_id__state__in=["three", "seven"])
        if eva_obj.count():
            morals_wind_flag = True
        team_leval = request.user.company.evaluationteam_set.all()
        if team_leval:
            if team_leval.first().team_leval == "1":
                company_id = 1001
            elif team_leval.first().team_leval == "2":
                company_id = 1002
            elif team_leval.first().team_leval == "3":
                company_id = 1003
            else:
                company_id = 1004
        else:
            company_id = request.user.company.id

        all_count = EvaluationOfMedicalEthics.objects.filter(~Q(state="draft"), year=year_list[0], apply_company_id=company_id).count()
        best_count = EvaluationOfMedicalEthics.objects.filter(~Q(state="draft"), year=year_list[0], apply_company_id=company_id, level="best").count()

        if all_count:
            compliance = round(all_count * 0.15)
            Proportion = round((best_count / all_count) * 100, 2)
            print("*****************", compliance, best_count)
            if compliance < best_count:
                summit_flag = "false"
            else:
                summit_flag = "true"
        else:
            Proportion = 0
            summit_flag = "false"
        print("===============", summit_flag)
        context = {"realname": real_name, "department": department, "position": position, "year_list": year_list, "year_num": year_num, "search_year": year_list[0],
                   "morals_wind_flag": morals_wind_flag, "all_count": all_count, "Proportion": Proportion, "summit_flag": summit_flag, "best_count": best_count}
        return render(request, 'medical_ethics/DepartmentSummary.html', context)

    def post(self, request):
        today = datetime.today()
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", "")  # 查询标题
        SearchYear = request.POST.get("SearchYear", today.year - 1)
        objs = EvaluationOpinion.objects.filter(Q(parent_id__apply_user__real_name__contains=search_data) | Q(parent_id__title__contains=search_data) | Q(parent_id__education__contains=search_data) |
                Q(parent_id__employ_date__contains=search_data) | Q(parent_id__birthday_date__contains=search_data) | Q(parent_id__job__contains=search_data) | Q(parent_id__political_status__contains=search_data) |
                Q(parent_id__professional_title__contains=search_data), audit_people=request.user, node='one', parent_id__year=SearchYear).order_by('create_time')
        if not objs.count() and (int(SearchYear) != today.year - 1):
            objs = EvaluationOpinion.objects.filter(Q(parent_id__apply_user__real_name__contains=search_data) | Q(parent_id__title__contains=search_data) | Q(parent_id__education__contains=search_data) | Q(parent_id__employ_date__contains=search_data) | Q(
                parent_id__birthday_date__contains=search_data) | Q(parent_id__job__contains=search_data) | Q(parent_id__political_status__contains=search_data) | Q(
                parent_id__professional_title__contains=search_data), audit_people=request.user, node='one', parent_id__year=today.year - 2).order_by('create_time')
        data_list = []
        for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]:
            if obj.parent_id.state == 'one':
                url_text = "审核"
            elif obj.parent_id.state == 'seven':
                url_text = "修改"
            else:
                url_text = "查看"

            if url_text == "修改":
                flow_url = '<a href="javascript:;" style="color: #EE2C2C;" onclick="SingleSubmission('+str(obj.parent_id.id)+')">提交</a> | <a class="plugin-action" id="' + str(obj.parent_id.id) + '" href="medical_ethics_detail_view?id=' + str(obj.parent_id.id) + '">'+url_text+'</a>'
            else:
                flow_url = '<a class="plugin-action" id="' + str(obj.parent_id.id) + '" href="medical_ethics_detail_view?id=' + str(obj.parent_id.id) + '">'+url_text+'</a>'

            one_dict = {'id': obj.parent_id.id, 'apply_user': obj.parent_id.apply_user.real_name, 'create_time': obj.parent_id.create_time.strftime("%Y-%m-%d %H:%M"), "title": obj.parent_id.title,
                 "professional_title": obj.parent_id.professional_title, "employ_date": obj.parent_id.employ_date, "job": obj.parent_id.job,
                 'level': obj.parent_id.get_level_display(), 'state': obj.parent_id.get_state_str(), 'url': flow_url}
            if obj.parent_id.get_state_str() != "完结":
                data_list.insert(0, one_dict)
            else:
                data_list.append(one_dict)
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class BatchSubmission(View):
    def post(self, request):
        id_list = request.POST.get("id_list", [])
        if id_list:
            for j in json.loads(id_list):
                first_obj = EvaluationOfMedicalEthics.objects.get(id=int(j))
                if not first_obj.item_list or not first_obj.total_score:
                    returnDict = {'code': 400, 'message': '提交流程中有未评分流程，请检查！'}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")

            for i in json.loads(id_list):
                obj = EvaluationOfMedicalEthics.objects.get(id=int(i))
                if obj.state == "one":
                    obj.state = 'three'
                    obj.save()
            returnDict = {'code': 200, 'message': '提交成功!'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        returnDict = {'code': 400, 'message': '请选择提交流程!'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class FallLevelView(View):
    def post(self, request):
        flow_id = request.POST.get("flow_id", '')           # 流程ID
        leval_select = request.POST.get("leval_select", '')           # 级别
        fall_opinion = request.POST.get("fall_opinion", '')           # 意见

        obj = EvaluationOfMedicalEthics.objects.get(id=int(flow_id))
        obj.level = leval_select
        obj.state = "five"
        obj.save()

        EvaluationOpinion.objects.create(parent_id=obj, audit_people=request.user, node='three', audit_note=fall_opinion, state="audit")

        returnDict = {'code': 200, 'message': '操作成功!'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class BatchApproval(View):
    def post(self, request):
        id_list = request.POST.get("id_list", [])
        if id_list:
            for i in json.loads(id_list):
                obj = EvaluationOfMedicalEthics.objects.get(id=int(i))
                obj.state = 'five'
                obj.save()

                EvaluationOpinion.objects.create(parent_id=obj, audit_people=request.user, node='three', audit_note="经过小组讨论，同意考核结果。", state="audit")
            returnDict = {'code': 200, 'message': '操作成功!'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        returnDict = {'code': 400, 'message': '请选择审批流程!'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class DownloadAssessment(View):
    def post(self, request):
        years = request.POST.get('years', None)
        CompanyObj = EvaluationOfMedicalEthics.objects.filter(state__in=['three', 'five'], year=years).values("apply_company_id").distinct()
        # ===========================================================构建表格数据===========================================================
        examine_data_list, serial = [], 1
        for dept in CompanyObj:
            if int(dept["apply_company_id"]) >= 1000:
                if int(dept["apply_company_id"]) == 1001:
                    company_name = "医德医风评选一组"
                elif int(dept["apply_company_id"]) == 1002:
                    company_name = "医德医风评选二组"
                elif int(dept["apply_company_id"]) == 1003:
                    company_name = "医德医风评选三组"
                else:
                    company_name = "医德医风评选四组"
            else:
                company_name = Company.objects.get(id=int(dept["apply_company_id"])).name
            examine_obj = EvaluationOfMedicalEthics.objects.filter(state__in=['three', 'five'], year=years, apply_company_id=dept["apply_company_id"]).order_by('create_time')
            # 优秀数据获取
            best_obj = examine_obj.filter(level='best')
            best_prople = ','.join([i.apply_user.real_name for i in best_obj])
            # =================================================================良好数据获取=================================================================
            good_obj = examine_obj.filter(level='good')
            good_prople = ','.join([i.apply_user.real_name for i in good_obj])
            # =================================================================一般数据获取=================================================================
            ordinary_obj = examine_obj.filter(level='ordinary')
            ordinary_prople = ','.join([i.apply_user.real_name for i in ordinary_obj])
            # =================================================================较差数据获取=================================================================
            bad_obj = examine_obj.filter(level='bad')
            bad_prople = ','.join([i.apply_user.real_name for i in bad_obj])
            examine_data_list.append({"company_name": company_name, "participate_number": examine_obj.count(), "best_prople": best_prople,
                 "best_count": best_obj.count(), "good_prople": good_prople, "ordinary_prople": ordinary_prople, "bad_prople": bad_prople, "serial": serial})
            serial += 1
        file_path = DownloadPublishTheResults().download_medical_ethics(examine_data_list, years)
        returnDict = {'code': 200, 'message': '查询成功!', "file_path": file_path.replace(os.getcwd(), "")}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class single_submission(View):
    def post(self, request):
        flow_id = request.POST.get('flow_id', None)
        obj = EvaluationOfMedicalEthics.objects.get(id=int(flow_id))
        obj.state = 'three'
        obj.save()
        returnDict = {'code': 200, 'message': '提交成功!'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class single_submit(View):
    def post(self, request):
        flow_id = request.POST.get('flow_id', None)
        obj = EvaluationOfMedicalEthics.objects.get(id=int(flow_id))
        obj.state = 'five'
        obj.save()
        EvaluationOpinion.objects.create(parent_id=obj, audit_people=request.user, node='three', audit_note="经过小组讨论，同意考核结果。", state="audit")
        returnDict = {'code': 200, 'message': '提交成功!'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class data_statistics(View):
    def post(self, request):
        years = request.POST.get('years', "")
        all_count = EvaluationOfMedicalEthics.objects.filter(year=int(years), state__in=["three", "four", "five"]).count()
        best_cunt = EvaluationOfMedicalEthics.objects.filter(level="best", year=int(years), state__in=["three", "four", "five"]).count()
        good_cunt = EvaluationOfMedicalEthics.objects.filter(level="good", year=int(years), state__in=["three", "four", "five"]).count()
        ordinary_cunt = EvaluationOfMedicalEthics.objects.filter(level="ordinary", year=int(years), state__in=["three", "four", "five"]).count()
        bad_cunt = EvaluationOfMedicalEthics.objects.filter(level="bad", year=int(years), state__in=["three", "four", "five"]).count()
        returnDict = {'code': 200, 'message': '查询成功!', "data": {"best_cunt": best_cunt, "good_cunt": good_cunt, "ordinary_cunt": ordinary_cunt,
        "bad_cunt": bad_cunt, "all_count": all_count, "years": years}}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ReturnModification(View):
    def post(self, request):
        present_id = request.POST.get('id', None)
        obj = EvaluationOfMedicalEthics.objects.get(id=int(present_id))
        obj.current_audit_users.clear()
        obj.audit_users_already.clear()
        EvaluationOpinion.objects.filter(parent_id=obj).delete()
        obj.state = "draft"
        obj.save()
        returnDict = {'code': 200, 'message': '操作成功!'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class committee_return(View):
    def post(self, request):
        present_id = request.POST.get('flow_id', None)
        obj = EvaluationOfMedicalEthics.objects.get(id=int(present_id))
        obj.audit_users_already.clear()
        try:
            red_obj = EvaluationOpinion.objects.get(parent_id=obj, node="one")
            obj.current_audit_users.add(red_obj.audit_people)
            red_obj.state = "unaudit"
            red_obj.audit_note = ""
            red_obj.save()
            print('==================', red_obj.state)
        except:
            red_obj = EvaluationOpinion.objects.filter(parent_id=obj, node="one")
            for tt in red_obj:
                obj.current_audit_users.add(tt.audit_people)
                tt.state = "unaudit"
                tt.audit_note = ""
                tt.save()
                print('==================tt', tt.state)
        obj.state = "one"
        obj.item_list = ""
        obj.total_score = ""
        obj.level = ""
        obj.save()
        returnDict = {'code': 200, 'message': '操作成功!'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class EvaluationReport(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            return redirect("/")
        team_obj = EvaluationTeam.objects.all()
        team_id_list = []
        for team in team_obj:
            team_id_list.append(team.company.id)
        dep_obj = Company.objects.filter(show='1').order_by('serial_number')
        dep_list = [{"name": "医德医风评选一组", "id": "1001"}, {"name": "医德医风评选二组", "id": "1002"}, {"name": "医德医风评选三组", "id": "1003"}, {"name": "医德医风评选四组", "id": "1004"}]
        for dep in dep_obj:
            if dep.id not in team_id_list:
                dep_list.append({"name": dep.name, "id": dep.id})
        return render(request, "medical_ethics/EvaluationReport.html", {'realname': real_name, 'position': position, 'department': department, "dep_list": dep_list})

    def post(self, request):
        dep_id = request.POST.get('dep_id', 1001)
        today = datetime.today()
        if today.month < 12:
            year_num = today.year - 1
        else:
            year_num = today.year
        team_id_list = []
        if int(dep_id) > 1000:
            if int(dep_id) == 1001:
                team_obj = EvaluationTeam.objects.filter(team_leval=1)
            elif int(dep_id) == 1002:
                team_obj = EvaluationTeam.objects.filter(team_leval=2)
            elif int(dep_id) == 1003:
                team_obj = EvaluationTeam.objects.filter(team_leval=3)
            else:
                team_obj = EvaluationTeam.objects.filter(team_leval=4)

            for team in team_obj:
                team_id_list.append(team.company.id)
        else:
            team_id_list.append(int(dep_id))
        user_obj = User.objects.filter(company__id__in=team_id_list, is_delete=0)
        data_list, serial = [], 1
        for i in user_obj:
            if not Dimission.objects.filter(user=i, state='end').count():
                tag_color = "#0b0b0b"
                one_dict = {"name": i.real_name, "dep": i.company.name, "serial": serial}
                obj = EvaluationOfMedicalEthics.objects.filter(~Q(state__in=["draft", "six"]), apply_user=i, year=year_num)
                if obj.count():
                    one_dict["fill"] = "是"
                    if obj.first().state in ["three", "four", "five"]:
                        one_dict["commit"] = "是"
                    else:
                        one_dict["commit"] = "否"
                        tag_color = "red"
                else:
                    one_dict["fill"] = "否"
                    one_dict["commit"] = "否"
                    tag_color = "red"
                one_dict["color"] = tag_color
                data_list.append(one_dict)
                serial += 1
        returnDict = {'code': 200, 'message': '操作成功!', "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class TopicRegistrationExport(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, "medical_ethics/TopicRegistrationExport.html", {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        data_list = []
        search_start_time = request.POST.get("search_start_time", '')
        search_end_time = request.POST.get("search_end_time", '')
        topic_year = request.POST.get("topic_year", '2025')

        if search_start_time and search_end_time:
            start_time = search_start_time + " 00:00:00"
            end_time = search_end_time + " 23:59:59"
            StartDateObject = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")
            EndDateObject = datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S")
            print(StartDateObject, EndDateObject)
            topic_obj = Topics.objects.filter(state='done', type='db', create_time__range=(StartDateObject, EndDateObject))
        else:
            topic_obj = Topics.objects.filter(state='done', type='db', iss_year=topic_year)

        for i in topic_obj[(int(page) - 1) * int(page_size):int(page) * int(page_size)]:
            meeting_number = f"{topic_year}年第{i.meetings_num}次党委会"
            MeetObj = i.topic_meeting_set.all().first()
            meeting_date = MeetObj.voteleader_set.all().first().create_time.strftime("%Y-%m-%d")
            topic_name = f'<a href="/personal-center/vote_detail.html?vote_id={MeetObj.id}&id={i.id}">{i.topics_name}</a>'
            submit_department = i.employee.company.name
            topic_number = i.number
            if i.HouseToParty_id:
                yb_topic_obj = Topics.objects.get(id=int(i.HouseToParty_id))
                price_dean_meeting = f"{yb_topic_obj.iss_year}年第{yb_topic_obj.meetings_num}次院长办公会"
            else:
                price_dean_meeting = "直接上党委会"
            data_list.append({
                "meeting_date": meeting_date, "meeting_number": meeting_number, "topic_name": topic_name, "submit_department": submit_department, "topic_number": topic_number,
                "price_dean_meeting": price_dean_meeting
            })

        returnDict = {'status': 'success', "totals": topic_obj.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class SummaryOfficialDocuments(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")

        search_year = request.GET.get("search_year", f"{datetime.today().year}")
        year_all = ConferenceMemo.objects.filter(state='seven', type='g').values("document_year").distinct()
        objs = ConferenceMemo.objects.filter(state='seven', type='g', document_year=search_year)
        document_list = []
        serial = 1
        for obj in objs:
            document_list.append({"title": obj.conference_memo_text, "number": obj.document_number, "serial": serial, "id": obj.id})
            serial += 1
        year_list = []
        for ii in year_all:
            year_list.append(ii["document_year"])
        return render(request, "medical_ethics/SummaryOfficialDocuments.html",
                      {'realname': real_name, 'position': position, 'department': department, "document_list": document_list, "year_list": year_list, "search_year": search_year})

    def post(self, request):
        search_year = request.POST.get("search_year", 1)
        objs = ConferenceMemo.objects.filter(state='seven', type='g', document_year=search_year)
        document_list = []
        serial = 1
        for obj in objs:
            document_list.append({"title": obj.conference_memo_text, "number": obj.document_number, "serial": serial, "id": obj.id})
            serial += 1
        file_path = create_excel(document_list, f"{search_year}年京医党发文件汇总")
        print(file_path)
        returnDict = {'status': 'success', "code": 200, "data": [], "file_path": file_path.replace(os.getcwd(), "")}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

def create_excel(datas, title):
    wb = Workbook()
    ws = wb['Sheet']
    xw = wb.active
    thick_side = Side(border_style="thin", color="000000")
    border = Border(top=thick_side, left=thick_side, right=thick_side, bottom=thick_side)
    ws.title = 'Sheet1'
    ws.merge_cells('A1:C1')
    ws.row_dimensions[1].height = 31
    top_left_cell = ws['A1']
    top_left_cell.value = f"{title}"
    top_left_cell.font = Font(b=True, color="000000", size=16)
    top_left_cell.alignment = Alignment(horizontal="center", vertical="center")

    ws['A2'] = '序号'
    ws['A2'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    ws['A2'].font = Font(b=True, color="000000")
    ws['A2'].alignment = Alignment(horizontal="center", vertical="center")
    ws['B2'] = '标题'
    ws['B2'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    ws['B2'].font = Font(b=True, color="000000")
    ws['B2'].alignment = Alignment(horizontal="center", vertical="center")
    ws['C2'] = '公文编号'
    ws['C2'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    ws['C2'].font = Font(b=True, color="000000")
    ws['C2'].alignment = Alignment(horizontal="center", vertical="center")
    ws.row_dimensions[2].height = 25

    line_list = ["A", "B", "C"]
    for j in range(1, 3):
        for k in line_list:
            xw[f'{k}{j}'].border = border

    row = 3
    for x in datas:
        ws[f'A{row}'].alignment = Alignment(horizontal="center", vertical="center")
        xw[f'A{row}'].border = border
        ws[f'B{row}'].alignment = Alignment(horizontal="left", vertical="center", wrap_text=True)
        xw[f'B{row}'].border = border
        ws[f'C{row}'].alignment = Alignment(horizontal="center", vertical="center")
        xw[f'C{row}'].border = border

        ws.cell(row, 1).value = x["serial"]
        ws.cell(row, 2).value = x["title"]
        ws.cell(row, 3).value = x["number"]
        ws.row_dimensions[row].height = 25
        row += 1

    ws.column_dimensions['A'].width = 10
    ws.column_dimensions['B'].width = 80
    ws.column_dimensions['c'].width = 28

    file_path = os.getcwd() + f"/media/document_db/SummaryOfficialDocuments.xlsx"
    if os.path.exists(file_path):
        os.remove(file_path)

    folder_path = os.getcwd() + f"/media/document_db"
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)
    wb.save(file_path)
    return file_path